package org.feng.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.feng.entity.CustomDict;
import org.feng.mapper.CustomDictMapper;
import org.feng.service.CustomDictService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 自定义字典服务实现
 *
 * @author feng
 */
@Service
public class CustomDictServiceImpl extends ServiceImpl<CustomDictMapper, CustomDict> implements CustomDictService {

    @Override
    public List<CustomDict> list(CustomDict dict) {
        LambdaQueryWrapper<CustomDict> queryWrapper = queryWrapper();
        if (Objects.nonNull(dict)) {
            // 字典ID不为空，查对应的字典数据和其直接子级的字典数据
            queryWrapper.and(Objects.nonNull(dict.getId()), query -> {
                query.eq(CustomDict::getId, dict.getId()).or().eq(CustomDict::getParentId, dict.getId());
            });

            // 字典key不为空，需要拦截匹配字典key
            queryWrapper.eq(StrUtil.isNotBlank(dict.getDictKey()), CustomDict::getDictKey, dict.getDictKey());
            // 字典name不为空，需要拦截模糊匹配字典name
            queryWrapper.like(StrUtil.isNotBlank(dict.getName()), CustomDict::getName, String.format("%%%s%%", dict.getName()));
        }

        return this.list(queryWrapper);
    }

    @Override
    public List<CustomDict> listChildrenById(Long dictId) {
        Assert.notNull(dictId, IllegalArgumentException::new);
        LambdaQueryWrapper<CustomDict> queryWrapper = queryWrapper();
        queryWrapper.eq(CustomDict::getParentId, dictId);
        return this.list(queryWrapper);
    }

    @Override
    public CustomDict getByDictKey(String dictKey) {
        LambdaQueryWrapper<CustomDict> queryWrapper = queryWrapper();
        queryWrapper.eq(CustomDict::getDictKey, dictKey);
        return this.getBaseMapper().selectOne(queryWrapper);
    }

    public LambdaQueryWrapper<CustomDict> queryWrapper() {
        return Wrappers.lambdaQuery();
    }
}
